<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>用户列表</title>
	<link rel="stylesheet" type="text/css" href="/static/layui/css/layui.css" />
	<link rel="stylesheet" type="text/css" href="/static/plugins/zTree/zTreeStyle/zTreeStyle.css"/>	
	<link rel="stylesheet" type="text/css" href="/static/common/common.css" />
	<style type="text/css">
		.layui-transfer-box{
			height:200px!important;
			overflow-y: overlay;
		}	
		.layui-table-body.layui-table-main tr .layui-table-cell{
			height: 130px;
   		    line-height: unset;
		}
	</style>
</head>
<body class="body-container">
	<div>
		<fieldset class="layui-elem-field layui-field-title" style="margin-top: 20px;">
			<legend>用户列表</legend>
		</fieldset>		
		<!-- <button type="button" class="layui-btn layui-btn-normal layui-btn-sm export-user-btn">导出用户</button>
		<button type="button" class="layui-btn layui-btn-sm import-user-btn">导入用户</button> -->
	</div>
			
	<!-- table表格数据 -->
	<div class="content-container">
		<table class="layui-hide" id="layerTable" lay-filter="layerTable"></table>
	</div>

	<script type="text/html" id="layuiTableToolbar">
  		<div class="layui-btn-container">
    				
  		</div>
	</script>
	
	<script src="/static/jquery/jquery-2.1.1.min.js" type="text/javascript"></script>
	<script src="/static/layui/layui.all.js" type="text/javascript"></script>
	<script src="/static/plugins/zTree/js/jquery.ztree.all.min.js" type="text/javascript"></script>
	<script src="/static/common/common.js" type="text/javascript"></script>
	<script type="text/javascript" th:inline="none">
	
		$(document).ready(function() {
		
		})
		
		// 导出
		$(document).on('click', '.export-user-btn', function() {
			layer.confirm('确定导出用户信息吗？',{title:'提示信息'}, function(index){
				window.location.href = "/excelExport/demoTest";	
				layer.close(index);		
			})
		})
		
		// 导入	
		$(document).on('click', '.import-user-btn', function() {
			layer.confirm('确定导入用户信息吗？',{title:'提示信息'}, function(index){
				window.location.href = "/excelImport/demoTest";	
				layer.close(index);	
			})
		})
		
		// table
		layui.use('table', function(){
	        var table = layui.table;
	        table.render({
	            elem: '#layerTable'	
	            ,url:'/sysUser/selectPageList'
	          	//,toolbar: '#layuiTableToolbar'
				//,height:600
				,method:'post'
				,limit:10
				,limits:[10,20,30]
				,where: {}
	            ,request: {
	                pageName: 'currentPage' //页码的参数名称，默认：page
	                ,limitName: 'pageSize' 	//每页数据量的参数名，默认：limit
	            }
	            ,response: {		
	                statusName: 'code' 		//数据状态的字段名称，默认：code
	                ,statusCode: 200 		//成功的状态码，默认：0
	                ,msgName: 'msg' 		//状态信息的字段名称，默认：msg
	                ,countName: 'total'  	//数据总数的字段名称，默认：count
	                ,dataName: 'dataObject' //数据列表的字段名称，默认：data
				}	
	            ,cols: [[		
	            	{field:'id',width:160, title: '唯一id'}
	                ,{field:'nickname',width:280, title: '用户信息', templet:
	                	function(res){	
	            			var html = "";
	            			html+='<p>昵     称 ： '+res.nickname+' </p>';
	            			html+='<p>手机 号 ： '+res.phone+' </p>';
	            			html+='<p>QQ 号： '+res.qq+' </p>';
	            			html+='<p>性  别   ： '+res.gender+' </p>';
	           				return html;	
	            		}
	                }
	                ,{field:'registerCode',width:220, title: '账号信息', templet:
	                	function(res){	
	            			var html = "";
	            			html+='<p>个性签名： '+res.description+' </p>';
	            			html+='<p>账号类型： '+getCommonUserType(res.userType)+' </p>';
	           				return html;	
	            		}
	                }
	                ,{field:'description',width:150, title: '注册码/邀请码', templet:
	                	function(res){	
	            			var html = "";
	            			
	            			html+='<p>注册码： '+res.registerCode+' </p>';
	            			html+='<p>邀请码： '+res.invitationCode+' </p>';
	           				return html;	
	            		}
	                }
	            	,{field:'wxOpenId',width:350, title: '微信', templet:
	                	function(res){	
	            			var html = "";
	            			html+='<p>wxOpenId： '+res.wxOpenId+' </p>';
	            			html+='<p>wxSessionKey： '+res.wxSessionKey+' </p>';
	            			html+='<p>latitude： '+res.latitude+' </p>';
	            			html+='<p>longitude： '+res.longitude+' </p>';
	            			html+='<p>地址： '+res.address+' </p>';
	           				return html;	
	            		}
	                }
	            	,{field:'createTime',width:220, title: '时间', templet:
	                	function(res){
	            			var html = "";
	            			html+='<p>创建： '+commonDateFormat(res.createTime,"yyyy-MM-dd hh:mm:ss")+' </p>';
	            			html+='<p>修改： '+commonDateFormat(res.updateTime,"yyyy-MM-dd hh:mm:ss")+' </p>';
	            			html+='<p>定位： '+commonDateFormat(res.locationUpdateTime,"yyyy-MM-dd hh:mm:ss")+' </p>';
	           				return html;	
	            		}
	                }
	                ,{field:'userStatus',width:100, title: '账号状态',templet: 
	                	function(res){			
	               			return getCommonUserStatus(res.userStatus);
	                	}
	                }
	                ,{field:'right',title: '操作', templet: 
	                	function(res){	
	                		var html = "";
	                		html += '<a class="layui-btn layui-btn-normal layui-btn-xs edit-user-btn" user-id='+res.id+'>';
            				html += '<i class="layui-icon layui-icon-edit"></i>编辑</a>';
	               			return html;	
	                	}
	                }	
	            ]]	
	            ,page: true
	            ,done: function(res, curr, count){	
	            	
	            }
	        });  
    	});
		
		
		// 添加角色
		$(document).on('click', '.edit-user-btn', function() {
			var userIdVal = $(this).attr("user-id");
			var index = layer.open({				
				type: 1 ,				  		// 0（信息框，默认）1（页面层）2（iframe层）3（加载层）4（tips层
				title: "添加菜单",					// title: ['文本', 'font-size:18px;']，数组第二项可以写任意css样式；如果你不想显示标题栏，你可以title: false
				area: ['70%', '60%'],		// 默认：'auto' 	自适应
				//shade: 1,				  		// 要想显示遮罩需要将这个  注释							
				skin: 'layui-layer-lan',  		// layer内置的skin有：layui-layer-lan layui-layer-molv
				maxmin: true,
				resize:true,		
				shadeClose:false,					
				content:initAddRoleHtml(),					
				btn: ['立即添加','取消'], 	
				btn1: function(){			

				},
				btn2: function(){				
					layer.close(index);		
				},
				cancel: function(){ 

				},		
				success: function(layers){		
					var form = layui.form;
					layers.addClass('layui-form');	
					layers.find('.layui-layer-btn0').attr('lay-filter', 'addRoleFrom').attr('lay-submit', '');//将按钮弄成能提交的
					form.render(); 	
					selectByUserIdRoleList(userIdVal);
					
					form.on('submit(addRoleFrom)', function (data) {	
						var treeObj = $.fn.zTree.getZTreeObj("menuZtreeId");
						var nodes = treeObj.getCheckedNodes(true);

						var menuZtreeIdAry = [];
						for (var i = 0; i < nodes.length; i++) {
							menuZtreeIdAry.push(nodes[i].id);
						}	
						if(menuZtreeIdAry.length<1){
							layer.msg("请选择菜单");
							return false;	
						}
						// 权限菜单
						data.field.menuZtreeIdList = menuZtreeIdAry.join();	
						$.ajax({			
							url: '/sysRole/addRoleInfo', 				// 请求的url地址	
							dataType: 'json', 							// 返回格式为json	
							data: data.field,
							type: 'post', 								// 请求方式		
							async: false,	
							success: function (res) {
								if (res.code == 200) {
									layer.msg("添加成功");	
									layer.close(index);	
									layui.table.reload('layerTable', { page: { curr: 1 }, where: { } });					
								}else{			
									layer.msg(res.msg);	
								}
							},		
							error: function () {

							}
						});
						return false;
					});	

				}	
			});
		})
		
		// 根据用户id查询角色列表
		function selectByUserIdRoleList(id){
			$.ajax({			
				url: '/sysRole/selectByUserIdRoleList', 				// 请求的url地址	
				dataType: 'json', 							// 返回格式为json	
				data: {'userId':id},
				type: 'post', 								// 请求方式		
				success: function (res) {
					console.log(res);
					if(res.code==200){
						initUserRoleTransfer(id,res.dataObject);
					}else{
						layer.msg(res.msg);	
					}
				},		
				error: function () {

				}
			});
		}
		
		// 初始化 用户角色 穿梭框
		function initUserRoleTransfer(userId,obj){
			var allRolelist = obj.allRolelist;
			var userRoleList = obj.userRoleList;
			
			var validMenuList = obj.validMenuList;
			
			// 所有的
			var allData = [];
			for (let index = 0; index < allRolelist.length; index++) {
				const element = allRolelist[index];
				var b = false;
				if(element.statusCode!='success'){
					b = true;
				}
				var transferInfo = {
					value:element.id,
					title:element.roleName,
					disabled:b
				}
				allData.push(transferInfo);
			}
			
			// 已有的角色
			var roleHtml = '';
			var selectedData = [];
			for (let index = 0; index < userRoleList.length; index++) {
				const element = userRoleList[index];
				selectedData.push(element.roleId);
					
				roleHtml+='<option value="'+element.roleId+'">'+element.roleName+'</option>';
			}	
			if(userRoleList.length>0){	
				$("#userRoleSelect").empty().append(roleHtml);	
				layui.form.render(); 	
			}
			
			// 初始化角色列表	
			initUserRoleSelectHtml(userRoleList,validMenuList)
			
			layui.use(['transfer', 'layer', 'util'], function(){
			  var $ = layui.$
			  ,transfer = layui.transfer
			  ,layer = layui.layer
			  ,util = layui.util;
			 	
			  //显示搜索框
			  transfer.render({
			    elem: '#transferId'
			    ,data: allData
			    ,title: ['未有角色', '已有角色']
			    //,showSearch: true
			    ,value: selectedData
			    ,onchange: function(obj, index){
			      console.log(obj);
			      //获得被穿梭时的数据
			      // layer.alert('来自 <strong>'+ index + '</strong> 的数据：'+ JSON.stringify(obj)); 
			      	
			      var roleIds = [];
			      
			      for (let index = 0; index < obj.length; index++) {
			    	  const element = obj[index]; 
			    	  roleIds.push(element.value);
			      }
			      // 刷新
			      saveTransferInfo(index,userId,roleIds);
			      
			    }
			  })	
			});
		}
		
		// 保存穿梭框  save
		function saveTransferInfo(index,userId,roleIds){
			
			var url = '/sysRole/deleteUserRole';
			if(index==0){	
				// 添加
				url = '/sysRole/addUserRole';
			}
			$.ajax({					
				url: url, 								// 请求的url地址	
				dataType: 'json', 						// 返回格式为json	
				data: {'userId':userId,'roleIds':roleIds.join()},	
				type: 'post', 							// 请求方式		
				async: false,	
				success: function (res) {
					if (res.code == 200) {
						layer.msg("保存成功");		
						//layer.close(index);		
						selectByUserIdRoleList(userId);			
					}else{			
						layer.msg(res.msg);	
					}
				},		
				error: function () {

				}
			});
		}
		
		// 初始化角色列表
		function initUserRoleSelectHtml(uObj,mObj){
			// 已有的角色
			var roleHtml = '';
			for (let index = 0; index < uObj.length; index++) {
				const element = uObj[index];
				roleHtml+='<option value="'+element.roleId+'">'+element.roleName+'</option>';
			}	
			if(uObj.length>0){	
				$("#userRoleSelect").empty().append(roleHtml);	
				layui.form.render(); 	
			}
			
			// 当前用户角色 权限列表
			ztree_nodes = [];
			for (let index = 0; index < mObj.length; index++) {
				const item = mObj[index];	
				ztree_nodes.push({ id:item.id, pId:item.pId, name:item.name,open:false,checked:item.checked});
			}		
			$.fn.zTree.init($("#menuZtreeId"), ztree_setting, ztree_nodes);
		}
		
		// 添加角色 html
		function initAddRoleHtml(){
			var html = "";		
			html+='<div style="margin: 40px 20px;">';	
			html+='<form class="layui-form" action="">';
				
			html+='<div class="layui-form-item">';
			html+='<div class="layui-inline">';
			html+='<label class="layui-form-label zdy-required">分配角色</label>';
			html+='<div class="layui-input-inline" style="width: 500px;">';
			html+='<div id="transferId"></div>';
			html+='</div>';
			html+='</div>';
			html+='</div>';
			
			html+='<div class="layui-form-item">';
			html+='<div class="layui-inline">';
			html+='<label class="layui-form-label zdy-required">角色名称</label>';
			html+='<div class="layui-input-inline input-inline-width">';
			
			html+='<select id="userRoleSelect" name="roleId" lay-verify="required" lay-filter="userRoleSelect">';
			html+='<option value=""></option>';
			html+='</select>';

			
			html+='</div>';
			html+='</div>';
			html+='</div>';
			
			
			// 菜单权限列表
			html+='<div class="layui-form-item">';		
			html+='<label class="layui-form-label zdy-required">菜单列表</label>';	
			html+='<div class="layui-input-inline">';		
			html+='<ul id="menuZtreeId" class="ztree"></ul>';
			html+='</div>';
			html+='</div>';
			html+='</form>';
			html+='</div>';
			return html;
		}
		
		layui.use('form', function () {
			var form = layui.form;	
			// 老客户
			form.on('select(userRoleSelect)', function(data){
				selectRoleIdValidMenuList(data.value);
			});				
		})
		
		// 查询角色列表
		function selectRoleIdValidMenuList(id){
			$.ajax({					
				url: '/sysRole/selectRoleIdValidMenuList', 								// 请求的url地址	
				dataType: 'json', 						// 返回格式为json	
				data: {'roleId':id},	
				type: 'post', 							// 请求方式		
				async: false,	
				success: function (res) {
					ztree_nodes = [];
					if (res.code == 200) {
						if(res.dataObject.length>0){
			        		$.each(res.dataObject,function(i,item){		
			        			ztree_nodes.push({ id:item.id, pId:item.pId, name:item.name,open:true,checked:item.checked});	
			        		})
		    			}						
					}else{			
						layer.msg(res.msg);	
					}
					$.fn.zTree.init($("#menuZtreeId"), ztree_setting, ztree_nodes);
				},		
				error: function () {

				}
			});
		}
		
		// 树节点
		var ztree_nodes;
			
		// 环境 ztree	
		var ztree_setting = {
		  check: {
		    enable: false
		  },
		  data: {
		    simpleData: {
		      enable: true
		    }
		  }
		};	
	</script>
</body>
</html>